<template>
  <div>
    <el-dialog
      :title="config.title"
      v-el-drag-dialog
      :visible="config.show===true"
      :close-on-click-modal="false"
      :before-close="handleClose"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="上级菜单：" prop="parentCatalog">
              <el-select
                v-model="form.parentCatalog"
                placeholder="请选择"
                ref="parentCatalogSelect"
                style="width: 100%"
              >
                <el-input
                  class="input"
                  placeholder="输入关键字进行过滤"
                  prefix-icon="el-icon-search"
                  v-model="parentCatalogFilter"
                  size="mini"
                  clearable
                ></el-input>
                <el-option hidden key="id" :value="form.parentCatalog" :label="form.parentCatalogName">
                </el-option>
                <el-tree
                  :data="param.parentCatalogTreeData"
                  :props="defaultProps"
                  @node-click="handleNodeClick"
                  :expand-on-click-node="false"
                  :check-on-click-node="true"
                  accordion
                  ref="tree"
                  node-key="id"
                  :default-expand-all="false"
                  :filter-node-method="filterNode"
                >

                  <span slot-scope="{ data }">
                    <span>{{ data.label }}</span>
                    <!-- 2022年3月31日 LQ 这个没什么用啊，先去掉
                     <el-tag
                          size="mini"
                          style="margin: 0 10px"
                          v-show="filterorgType(data.tag)"
                      >{{ filterorgType(data.tag) }}</el-tag
                      >-->
                  </span>
                </el-tree>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="时相：">
              <el-date-picker type="date" placeholder="选择时相" v-model="form.date" format="yyyy-MM-dd"
                              value-format="yyyy-MM-dd" style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="服务名称：" prop="name">
              <el-input v-model="form.name" type="text"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务类型：" prop="serviceType" placeholder="请选择服务类型">
              <el-select v-model="form.serviceType" filterable value-key style="width: 100%">
                <el-option v-for="serviceType in param.serviceTypes" :key="serviceType.value" :label="serviceType.name"
                           :value="serviceType.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="服务地址：" prop="url">
              <el-input v-model="form.url" type="text"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="投影类型：" prop="prjType">
              <el-select v-model="form.prjType" value-key="value" style="width: 100%" placeholder="请选择投影类型">
                <el-option v-for="prjType in param.prjTypes" :key="prjType.value" :label="prjType.name"
                           :value="prjType.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色权限：">
              <el-select v-model="form.roles" value-key="value" style="width: 100%" ref="rolesSelect" multiple clearable
                         filterable placeholder="请选择允许访问的角色"
              >
                <el-option v-for="role in param.portalRoles" :key="role.value" :label="role.name"
                           :value="role.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="可见级别：">
          <el-col :span="6">
            <el-input v-model="form.zmin" type="text" placeholder="最小可见级别" style="width: 100%"></el-input>
          </el-col>
          <el-col class="line" :span="1">-</el-col>
          <el-col :span="6">
            <el-input v-model="form.zmax" type="text" placeholder="最大可见级别" style="width: 100%"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="四至：">
          <el-row>
            <el-col :span="6">
              <el-input v-model="form.xmin" type="text" placeholder="XMIN"></el-input>
            </el-col>
            <el-col class="line" :span="1">&ensp;</el-col>
            <el-col :span="6">
              <el-input v-model="form.ymin" type="text" placeholder="YMIN"></el-input>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-input v-model="form.xmax" type="text" placeholder="XMAX"></el-input>
            </el-col>
            <el-col class="line" :span="1">&ensp;</el-col>
            <el-col :span="6">
              <el-input v-model="form.ymax" type="text" placeholder="YMAX"></el-input>
            </el-col>
          </el-row>
        </el-form-item>
        <el-row>
          <el-col :span="7" v-show="config.itemShow.isLabel">
            <el-form-item label="是否注记：" prop="isLabel">
              <el-switch v-model="form.isLabel"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="自动加载：" prop="isAutoLoad">
              <el-switch v-model="form.isAutoLoad"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="是否可用：" prop="isValid">
              <el-switch v-model="form.isValid"></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="图例：">
          <el-col :span="8">
            <el-upload
              ref="legendUpload"
              class="upload-demo"
              :action="' '"
              accept=".png,.jpg,.jpeg,.gif"
              :auto-upload="false"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-change="legendHandleChangeImg"
              :file-list="legendFileList"
              :show-file-list="false"
            >
              <el-button slot="trigger" size="small" type="primary">上传图片</el-button>
              <!--                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
            </el-upload>
          </el-col>
          <el-col :span="16">
            <template v-if="hasLegend">
              <el-image :src="legendUrl" :preview-src-list="[legendUrl]" style="height: 30px;"
              ></el-image>
              <el-link class="upload-img-linkText" type="success" :href="legendUrl" target="_blank">{{form.legend}}</el-link>
            </template>
          </el-col>
          <!--          <el-col :span="4">-->
          <!--            <el-button size="small" type="primary" @click="legendFileView">预览</el-button>-->
          <!--          </el-col>-->
        </el-form-item>
        <el-row>
          <el-form-item label="图标名称：">
            <el-col :span="8">
              <el-upload
                ref="catalogIconUpload"
                class="upload-demo"
                :action="' '"
                accept=".png,.jpg,.jpeg,.gif"
                :auto-upload="false"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-change="catalogIconHandleChangeImg"
                :file-list="catalogIconFileList"
                :show-file-list="false"
              >
                <el-button slot="trigger" size="small" type="primary">上传图片</el-button>
                <!--                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
              </el-upload>
            </el-col>
            <el-col :span="16">
              <template v-if="hasCatalogIcon">
                <el-image :src="catalogIconUrl" :preview-src-list="[catalogIconUrl]"
                          style="height: 30px;"
                ></el-image>
                <el-link class="upload-img-linkText" type="success" :href="catalogIconUrl" target="_blank">{{form.enflag}}</el-link>
              </template>
            </el-col>
          </el-form-item>
          <el-col :span="24">
            <el-form-item label="说明：">
              <el-input type="textarea" :rows="2" v-model="form.explain" placeholder="服务的扩展说明"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-dialog width="80%" title="测试地图" :visible.sync="testMapDialogShow" :close-on-click-modal="false"
                 append-to-body
      >
        <component :is="testMapService" :config="testMapConfig"></component>
      </el-dialog>
      <span slot="footer" class="dialog-footer">
				<el-button type="primary" @click="handleOk">{{ config.okBtnText }}</el-button>
				<el-button @click="handleTest">测试</el-button>
				<el-button @click="handleConnect">连接</el-button>
				<el-button @click="handleClose">取消</el-button>
			</span>
    </el-dialog>
  </div>
</template>

<script>
import elDragDialog from '@/directive/el-dragDialog/'
import bus from '@/utils/bus'
import { insertResource, updateResource, uploadCatalogIconFile, uploadLegendFile } from '@/api/resource/resourceCatalog'
import { requestBaseUrl } from '@/utils/request'
import * as gcf from '@/utils/Global/GlobalCommonFunction'

export default {
  name: 'editCatalogService',
  data() {
    return {
      parentCatalogFilter: '',
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      legendFileList: [],
      catalogIconFileList: [],
      rules: {
        parentCatalog: [{ required: true, message: '请选择上级菜单', trigger: 'blur' }],
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        serviceType: [{ required: true, message: '请选择服务类型', trigger: 'blur' }],
        url: [{ required: true, message: '请输入地址', trigger: 'blur' }],
        prjType: [{ required: true, message: '请选择投影类型', trigger: 'blur' }]
      },
      testMapDialogShow: false,
      testMapService: undefined,
      testMapConfig: {}
    }
  },
  directives: {//到这里了，看看自定义组件怎么个用法
    elDragDialog
  },
  props: {
    config: {
      type: Object,
      default() {
        return {
          title: '',
          show: false,
          itemShow: {
            isLabel: false
          },
          okBtnText: '确定'
        }
      }
    },
    param: {
      type: Object,
      default() {
        return {
          parentCatalogTreeData: [],
          portalRoles: [],
          prjTypes: [],
          serviceTypes: []
        }
      }
    },
    form: {
      type: Object,
      default() {
        return {
          id: '',
          operatetype: '',
          parentCatalog: '',
          parentCatalogName: '', // select框显示的name
          isValid: true,
          isLabel: false,
          name: '',
          serviceType: '',
          roles: [],
          date: '',
          url: '',
          zmax: '',
          zmin: '',
          xmax: '',
          xmin: '',
          ymax: '',
          ymin: '',
          legend: '',//图例地址
          isAutoLoad: false,
          prjType: '',
          sortid: 1,
          enflag: '',//图标地址
          explain: ''
        }
      }
    }
  },
  computed: {
    legendUrl() {
      if (this.hasLegend) {
        return requestBaseUrl + this.form.legend
      }else{
        return "";
      }
    },
    hasLegend() {
      if (this.form.legend) {
        return gcf.IsNotNullStr(this.form.legend)
      }else{
        return false;
      }
    },
    hasCatalogIcon() {
      if (this.form.enflag) {
        return gcf.IsNotNullStr(this.form.enflag)
      }else{
        return false;
      }
    },
    catalogIconUrl() {
      if (this.hasCatalogIcon) {
        return requestBaseUrl + this.form.enflag
      }else{
        return "";
      }
    }
  },
  beforeMount() {
    if(!this.form.hasOwnProperty("legend")){
      this.form.legend="";
    }
    if(!this.form.hasOwnProperty("enflag")){
      this.form.enflag="";
    }
  },
  methods: {
    handlePreview(file) {
      console.log(file)
    },
    handleRemove(file, legendFileList) {
      console.log(file)
    },
    legendHandleChangeImg(file, legendFileList) {
      let that = this
      that.legendFileList = legendFileList
      const typeArr = ['image/png', 'image/gif', 'image/jpeg', 'image/jpg']
      const isJPG = typeArr.indexOf(file.raw.type) !== -1
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isJPG) {
        that.$message.error('只能上传图片！')
        that.$refs.legendUpload.clearFiles()
        that.legendFileList = []
        return
      }
      if (!isLt5M) {
        that.$message.error('上传图片大小不能超过 5MB！')
        that.$refs.legendUpload.clearFiles()
        that.legendFileList = []
        return
      }
      const legendFile = file.raw
      const formData = new FormData()
      formData.append('file', legendFile)
      uploadLegendFile(formData).then(res => {
        that.form.legend = res.legendPath;
        that.$forceUpdate();
      }).catch(resp => {
        console.log('uploadLegendFile', resp.status + ',' + resp.statusText)
      })
    },
    catalogIconHandleChangeImg(file, iconFileList) {
      let that = this
      that.catalogIconFileList = iconFileList
      const typeArr = ['image/png', 'image/gif', 'image/jpeg', 'image/jpg']
      const isJPG = typeArr.indexOf(file.raw.type) !== -1
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isJPG) {
        that.$message.error('只能上传图片！')
        that.$refs.catalogIconUpload.clearFiles()
        that.catalogIconFileList = []
        return
      }
      if (!isLt5M) {
        that.$message.error('上传图片大小不能超过 5MB！')
        that.$refs.catalogIconUpload.clearFiles()
        that.catalogIconFileList = []
        return
      }
      const iconFile = file.raw
      const formData = new FormData()
      formData.append('file', iconFile)
      uploadCatalogIconFile(formData).then(res => {
        that.form.enflag = res.catalogIconPath;
        that.$forceUpdate();
      }).catch(resp => {
        console.log('uploadCatalogIconFile', resp.status + ',' + resp.statusText)
      })
    },
    legendFileView() {
    },
    handleClose() {
      let that = this
      that.config.show = false
    },
    handleTest() {
      let that = this
      that.testMapConfig = {
        url: that.form.url,
        sys: 'EPSG:' + that.form.prjType,
        name: that.form.name,
        id: 'testLayer',
        type: parseFloat(that.form.serviceType),
        zIndex: 1
      }
      that.testMapService = resolve => require(['@/components/Map/mapService.vue'], resolve)
      that.testMapDialogShow = true
    },
    handleConnect() {
      let that = this
      let layerInfo = new ol.supermap.LayerInfoService(that.form.url)
      that.$message(layerInfo)
    },
    /**
     * 添加
     */
    handleOk() {
      let that = this
      let param = {
        'pid': that.form.parentCatalog,
        'name': that.form.name,
        'servicetypevalue': parseFloat(that.form.serviceType),
        'url': that.form.url,
        'xmin': parseFloat(that.form.xmin),
        'ymin': parseFloat(that.form.ymin),
        'zmin': parseInt(that.form.zmin),
        'xmax': parseFloat(that.form.xmax),
        'ymax': parseFloat(that.form.ymax),
        'zmax': parseInt(that.form.zmax),
        'legend': that.form.legend,
        'sys': parseInt(that.form.prjType),
        'sortid': that.form.sortid,
        'roleid': that.form.roles.join(','),
        'dates': that.form.date,
        'isvalid': that.form.isValid ? 1 : 0,
        'autoload': that.form.isAutoLoad ? 1 : 0,
        'enflag': that.form.enflag,
        'explain': that.form.explain
      }
      if (that.form.operatetype == 'updateService') {
        param.id = that.form.id
        updateResource(param).then((res) => {
          bus.$emit('refreshResourceCatalog')
          that.config.show = false
        }).catch(resp => {
          console.log('updateResourceCatalog', resp.status + ',' + resp.statusText)
        })
      }
      if (that.form.operatetype == 'insertService') {
        insertResource(param).then((res) => {
          bus.$emit('refreshResourceCatalog')
          that.config.show = false
        }).catch(resp => {
          console.log('insertResourceCatalog', resp.status + ',' + resp.statusText)
        })
      }
    },

    // 结构树点击事件
    handleNodeClick(currentData) {
      let that = this
      that.form.parentCatalog = currentData.id // select绑定值为点击的选项的value
      that.form.parentCatalogName = currentData.label // input中显示值为label
      that.parentCatalogFilter = '' // 点击后搜索框清空
      that.$refs.parentCatalogSelect.blur() // 点击后关闭下拉框，因为点击树形控件后select不会自动折叠

    },
    // 模糊查询（搜索过滤），实质为筛选出树形控件中符合输入条件的选项，过滤掉其他选项
    filterNode(value, data) {
      if (!value) return true
      let filterRes = data.label.indexOf(value) !== -1
      return filterRes
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .line {
  text-align: center;
}

::v-deep .el-form-item {
  //margin-bottom: 10px;
}
</style>
<style lang="css" scoped>
::v-deep input[type="file"] {
  display: none;
}
</style>
